import {
  Controller,
  HttpException,
  HttpStatus,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import SysUser from 'src/entities/users/sys-user.entity';
import { User } from 'src/interface/userInterface';
import { encript } from 'src/utils/encripttion';
@Injectable()
@Controller('user')
export class UsersService {
  constructor(
    @InjectRepository(SysUser)
    private readonly usersRepository: Repository<SysUser>,
  ) {}
  /**
   *
   * @param createUserDto 新增用户
   * @returns 用户是否新增成功
   */
  async createUser(createUserDto: User) {
    try {
      if (!createUserDto.username) {
        const res = {
          status: 202,
          data: [],
          message: '请输入用户名',
        };
        throw new HttpException(res, HttpStatus.OK);
      }
      if (!createUserDto.password) {
        const res = {
          status: 202,
          data: [],
          message: '请输入密码',
        };
        throw new HttpException(res, HttpStatus.OK);
      }
      // 1 查询当前的用户是否存在
      const existingRecord = await this.usersRepository.findOne({
        where: { username: createUserDto.username }, // 替换为实际的唯一标识字段和值
      });

      if (existingRecord) {
        const res = {
          status: 202,
          data: [],
          message: '用户已经存在',
        };
        throw new HttpException(res, HttpStatus.OK);
      }
      // 如果没有存在则进行添加
      const user = await this.usersRepository.save(createUserDto);
      if (user) {
        const res = {
          status: 200,
          data: [],
          message: '用户注册成功',
        };
        throw new HttpException(res, HttpStatus.OK);
      } else {
        const res = {
          status: 202,
          data: [],
          message: '用户注册失败',
        };
        throw new HttpException(res, HttpStatus.OK);
      }
    } catch (error) {
      const res = {
        status: 205,
        data: [],
        message: '用户注册失败' + error,
      };
      throw new HttpException(res, HttpStatus.OK);
    }
  }
  /**
   *
   * @param createUserDto 用户登录
   * @returns 用户登录成功返回token
   */
  async userLogin(createUserDto: User) {
    try {
      if (!createUserDto.username) {
        return {
          status: 202,
          message: '请输入用户名',
        };
      }
      if (!createUserDto.password) {
        return {
          status: 202,
          message: '请输入密码',
        };
      }
      // 1 查询当前的用户是否存在
      const user = await this.usersRepository.findOne({
        where: { username: createUserDto.username }, // 替换为实际的唯一标识字段和值
      });
      if (!user) {
        return {
          status: 202,
          message: '用户不存在',
        };
      }
      const isPasswordValid = this.comparePasswords(
        createUserDto.password,
        user.psalt || '1',
        user.password,
      );
      if (!isPasswordValid) {
        return {
          status: 205,
          message: '密码错误',
        };
      }

      return {
        status: 200,
        message: '登录成功',
        data: isPasswordValid,
      };
    } catch (error) {
      return {
        status: 200,
        message: '登录失败' + error,
      };
    }
  }

  ceshi() {
    const res = {
      data: ['data'],
    };
    throw new HttpException(res, HttpStatus.OK);
  }
  comparePasswords(
    password: string,
    psalt: string,
    hashedPassword: string,
  ): boolean {
    // 加密输入密码
    const derivedKeyBuffer = encript(password, psalt);
    // 将加密后的密码与存储的密码进行比对
    return derivedKeyBuffer === hashedPassword;
  }
}
